package cn.itcast.bos.web.action.system;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.MenuService;
import cn.itcast.bos.web.action.common.BaseAction;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
@ParentPackage("struts-default")
@Namespace("/")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MenuAction extends BaseAction<Menu> {

    @Autowired
    private MenuService menuService;

    @Action(value = "menu_list")
    public void findAll() {
        List<Menu> menus = menuService.findAll();
        writeJson(menus);
    }

    @Action(value = "menu_save", results = {@Result(name = "success", location = "./pages/system/menu.html", type = "redirect")})
    public String save() {
        Menu parentMenu = model.getParentMenu();
        if (parentMenu != null && parentMenu.getId() == 0) {
            model.setParentMenu(null);
        }
        menuService.save(model);
        return SUCCESS;
    }

    @Action(value = "menu_showByUser")
    public void showByUser(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        List<Menu> menus = menuService.findByUser(user);
        writeJson(menus);
    }
}
